package com.cskaoyan.common.servlet;


import com.cskaoyan.util.JsonUtil;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

/**
 * 公用Servlet
 * 不要重写service方法，否则会接收除Get和Post外的请求
 *
 * @author 侯嘉
 * @since 2024/04/09 22:36
 */
public class CommonServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            commonService(request, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            commonService(request, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 使用反射，调用子类Servlet中与最后一段URI同名的方法
     */
    private void commonService(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String uri = request.getRequestURI();
        String methodName = uri.substring(uri.lastIndexOf("/") + 1);
        Method method = this.getClass().getDeclaredMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
        method.setAccessible(true);
        Object result = method.invoke(this, request, response);
        method.setAccessible(false);
        if (result != null) {
            response.getWriter().write(JsonUtil.write(result));
        }
    }

}
